from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework import generics
from . import serializers
from django.core.mail import send_mail
from django.conf import settings
# Create your views here.
from django.views import View
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.users.serializers import UserCreateSerializer
from meiduo.apps.users.models import User
# from .models import User


# class index(View):
#     def get(self,request):
#
#         return HttpResponse("美多商城全新起航")


class UsernameCountView(APIView):
    def get(self, request, username):
        # 判断用户名是否存在：根据用户名在数据库中做统计
        count = User.objects.filter(username=username).count()
        return Response({
            'username': username,
            'count': count
        })


class MobileCountView(APIView):
    def get(self, request, mobile):
        # 判断手机号是否存在：统计
        count = User.objects.filter(mobile=mobile).count()
        return Response({
            'mobile': mobile,
            'count': count
        })


class UserCreateView(CreateAPIView):
    # queryset =
    serializer_class = UserCreateSerializer

class UserDetailView(generics.RetrieveAPIView):
    # queryset =
    serializer_class = serializers.UserDetailSerializer
    #必须登录
    permission_classes = [IsAuthenticated]

    # 默认获取一个对象的方法为：根据主键查询
    # 当前逻辑为：哪个用户登录，则显示这个用户的信息
    def get_object(self):
        return self.request.user

class EmailView(generics.UpdateAPIView):
    serializer_class = serializers.EmailSerializer
    permission_classes = [IsAuthenticated]
    def get_object(self):
        return self.request.user
class EmailVerifyView(APIView):
    def get(self, request):
        # 接收数据
        serializer = serializers.EmailVerifySerializer(data=request.query_params)
        # 验证
        if serializer.is_valid():
            # 保存修改
            serializer.save()
            return Response({"message": "OK"})
        # 错误提示
        return Response({'message': serializer.errors})

class index(View):
    def get(self,request):
        print("0")
        msg = '<a href="http://www.itcast.cn/subject/pythonzly/index.shtml" target="_blank">点击激活</a>'
        send_mail('注册s激活', '', settings.EMAIL_FROM, ['baichuangege@163.com'], html_message=msg)
        print("1")
        return   HttpResponse("邮箱发送成功")
